package chapter16;

import chapter11.Role;
import chapter13.UserService;
import chapter16.exception.RoleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-04-20 下午2:14
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/getRole")
    @ResponseBody
    public Role getRole(Long id) {
        Role role = userService.getRole(id);
        if (role == null) {
            throw new RoleException();
        }
        return role;
    }

    @RequestMapping("/updateRole")
    @ResponseBody
    public Map<String, Object> updateRole(Role role) {
        LOGGER.info(role.toString());
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("msg", "update success");
        return result;
    }

    /*当同时存在拦截器和控制器内自定义异常处理时，会优先使用类内部自定义的处理方法*/
    @ExceptionHandler(RoleException.class)
    public String HandleRoleException(Exception e) {
        return "exception2";
    }
}
